<?php
/**
 * MPE个人中心 -- 个人信息
 * @Author Liuyi
 * @name MemberAction
 * @Create 2016-11-1 15:16:14
 * @Copyright MPE.Fiidee.Monda.Cn
 */

namespace member\action;

use api\utils\PayApiClient;
use herosphp\core\Log;
use herosphp\http\HttpRequest;
use herosphp\session\Session;
use herosphp\utils\AjaxResult;
use herosphp\bean\Beans;
use herosphp\core\Loader;
use herosphp\utils\ArrayUtils;
use herosphp\string\StringUtils;
class MemberAction extends CommonAction
{

    protected $serviceBean = "member.member.service";
    protected $member_id = null;

    public function __construct()
    {
        parent::__construct();
        $this->member_id = $this->_user->id;
    }

    public function index(HttpRequest $request)
    {
        //var_dump($_SESSION);
        $u = $this->_user->getMyInfo();
        $this->assign('user', $u);
        $this->setView('person/person_index');
    }

    /**
     * 资质审核页面,待删除
     * @param HttpRequest $request
     */
    /*public function aptitude(HttpRequest $request)
    {

        $this->setView('person/person_aptitude');
    }*/

    /**
     * 实际执行资质审核过程，资质审核页面数据发送到此处
     * @param HttpRequest $request
     */
    public function do_aptitude(HttpRequest $request)
    {
        //var_dump($_POST);die;
        if( $_SERVER['REQUEST_METHOD'] !== 'POST' ){
            echo "<h1>Access Deny!</h1>";die;
        }
        $companyData = $request -> getParameter('data');
        $companyData['register_capital'] = $companyData['register_capital']?$companyData['register_capital']:'0';
        $companyData['prov'] = $request -> getParameter('province');
        $companyData['city'] = $request -> getParameter('city');
        $companyData['dist'] = $request -> getParameter('dist')?$request -> getParameter('dist'):"0";
        if($companyData['mobile'] != "") {
            if (!preg_match('/^\d{11}$/', $companyData['mobile'])) {
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "法定代表人手机输入错误", null);
            }
        }
        $main_business = $request -> getParameter("main_business");
        $companyData['main_business'] = StringUtils::jsonEncode($main_business);
        $companyData['userid'] = $this -> _user -> __get('dasu_pay_id');
        $companyData['addtime'] = date("Y-m-d H:i:s");
        $companyData['updatetime'] = date("Y-m-d H:i:s");
        $url = 'api/user/userAuth';
        $result = PayApiClient::send($url, array('companyData' => $companyData) );
        if ( $result->isSucess() ) {
            $temp['ischecked'] = 1;
            $this -> _user ->updateSignInfo();
            $this -> _user ->updateCompany();
            Log::info('提交资质审核成功');
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,"提交成功，请耐心等待审核！",null);
        } else {
            Log::error("提交资质失败，接口返回：".$result->getMessage());
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "提交失败，请重试！", null);
        }
        $this->setView('person/person_aptitude');
    }

    /**
     * 账户安全页面
     * @param HttpRequest $request
     */
    public function safe(HttpRequest $request)
    {

		$signInfo = $this->_user->getSignInfo();
		$level = 2;

        $level += ($signInfo['ischecked'] == 2) + ($signInfo['sign_status'] == 1) + (!!$signInfo['tradepass']);
        $this->assign('level', $level);
        $company = $this -> _user -> getCompany();
        //var_dump($signInfo);
        $this->assign('company', $company);
        $this->assign('signInfo', $signInfo);
        $this->setView('person/person_save');
    }

    /**
     * 实名认证
     * @param HttpRequest $request
     */
    public function auth(HttpRequest $request)
    {
        $payId = $this->_user->__get('dasu_pay_id');
        $ischecked = $this->_user->getSignInfo('ischecked');
        //$companyInfo = $this -> _user->getCompany();
        //var_dump($companyInfo);
        //$this -> assign('types', $this -> _user -> getType());
        //$this -> setView('person/person_aptitude');
        if ($payId) {
            if ( $ischecked ) {

                //提交了资质认证，如果SESSION有，就取SESSION，如果没有就去SaaS中心取
                if( $this -> _user -> getCompany() ){
                    $this -> assign("companyInfo",$this -> _user -> getCompany());
                }else {
                    $result = PayApiClient::send("api/user/getCompanyInfo", array('userid'=>$payId));
                    if ($result->isSucess()) {
                        $data = $result -> getItem();
                        $data['main_business'] = StringUtils::jsonDecode($data['main_business']);
                        $this -> _user -> updateCompany($data);
                        $this->assign("companyInfo", $data);
                    } else {
                        Log::error("获取公司信息失败,接口返回:".$result -> getMessage());
                        $this -> assign("error",true);
                    }
                }

                //审核中,ischecked=1
                if( $ischecked == "1" ){
                    $this -> assign("check",true);
                }
                $this->setView('person/person_aptitudeDone');

                //审核不通过，ischecked=3,可以编辑
                //var_dump($this -> _user -> getCompany());
                if( $ischecked == "3" ){
                    $this -> assign("check_note",$this -> _user ->getSignInfo("check_note"));
                    $this -> assign('types', $this -> _user -> getType());
                    $this -> setView('person/person_aptitude');
                }
            }else {
                //提交了注册或绑定，但是没有做资质认证的用户
                $this -> assign('types', $this -> _user -> getType());
                $this -> setView('person/person_aptitude');
            }
        } else {
            //未点击绑定/注册的用户
            $this->setView('person/person_real');
        }
    }

    /**
     * 实名认证下的注册页面
     * @param HttpRequest $request
     */
    public function reg(HttpRequest $request)
    {
        $payId = $this->_user->__get('dasu_pay_id');
        if( $payId ) {
            $this->auth($request);
        } else {
            $this->setView('person/person_reg');
        }
    }

    /**
     * 银行签约页面
     * @param HttpRequest $request
     */
    public function bankSign(HttpRequest $request)
    {
        //$this->setView('person/person_bankSign');return false;
        $signInfo = $this->_user->getSignInfo();
        if( $signInfo['ischecked'] !=2 ){
            //echo "<script>alert('你还没有签约，正在跳转！')</script>";
           // $this -> auth($request);
            $message = "您还未完善实名认证信息，或实名认证信息正审核中，请稍后再进行银行签约！";
            $url = "/member/member/auth";
            $this -> message($message,$url);

        }else {
            if ($signInfo['sign_status'] == 1) {
                $signInfo['card_no'] = substr_replace($signInfo['card_no'], "***********", 4, 11);
                $this->assign("signInfo", $signInfo);
                $this->setView("person/person_bankSignDone");
            } else {
                $this -> assign("authName",$signInfo['company']);
                $this->setView('person/person_bankSign');
            }
        }
    }

    /**
     * 签约银行
     * @param HttpRequest $request
     */
    public function do_signBank(HttpRequest $request)
    {
        $signData['payway'] = $request -> getParameter('payway');
        if( $signData['payway'] == 0 ){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"请先选择支付通道",null);
        }
        $user_id = $this ->_user ->__get('dasu_pay_id');
        $signData['virtual_name'] = $request -> getParameter('legal_person');
        $signData['sign_bank_branch'] = $request -> getParameter('sign_bank_branch');
        $signData['sign_bank_code'] = $request -> getParameter('sign_bank_code');
        $signData['sign_bank_id'] = $request -> getParameter('sign_bank_id');
        $signData['card_no'] = $request -> getParameter('card_no');

        $url = "api/user/signBank";
        $result = PayApiClient::send($url, array('userid'=>$user_id,'signData'=>$signData));
        if ( $result->isSucess() ) {
            $service = Beans::get('member.member.service');
            $service -> update(array('sign_status'=>1),$this->_user->__get('id'));
            $this->_user->updateSignInfo();//重新抓取saas数据
            Log::info("用户".$user_id." 签约成功");
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,"签约成功",null);
        } else {
            Log::error($user_id."签约失败，接口返回:".$result->getMessage());
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "签约失败，请联系客服！", null);
        }
    }

    /**
     * 解约银行处理操作
     * @param HttpRequest $request
     */
    public function do_unSignBank(HttpRequest $request)
    {
        $userid = $this -> _user -> __get('dasu_pay_id');
        $url = "api/user/unSignBank";
        $result = PayApiClient::send($url, array('userid'=>$userid));
        if ($result->isSucess()) {
            $service = Beans::get('member.member.service');
            $service -> update(array('sign_status'=>2),$this->_user->__get('id'));
            $this->_user->updateSignInfo();//重新抓取saas数据
            Log::info('用户'.$userid."解约成功");
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,"解约成功",null);
        } else {
            Log::error('用户'.$userid."解约失败，接口返回:".$result -> getMessage());
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"解约失败，请确定附属账号余额为零",null);
        }
    }

    /**
     * 银行列表，Ajax调用返回
     * @param HttpRequest $request
     */
    public function loadBanks(HttpRequest $request)
    {
        if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
            echo "<h1>Access Deny!</h1>";
            die;
        }
        $params = array('conditions' => "");
        $url = "api/bank/getBanks";
        $params['fields']="*";
        $params['order']="null";
        $params['page']='1';
        $params['pagesize']='2147483648';
        $result = PayApiClient::send($url, $params);
        if ($result->isSucess()) {
            $items = $result->getItems();
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "加载银行成功", $items);
        } else {
            Log::error("加载银行失败，接口返回：".$result->getMessage());
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, $result->getMessage(), null);
        }
    }

    /**
     * 加载银行支行列表页,Ajax调用返回
     * @param HttpRequest $request
     */
    public function getBankBranches(HttpRequest $request)
    {
        if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
            echo "<h1>Access Deny!</h1>";
            die;
        }
        $bankId = $request->getParameter('bank_id', 'trim');
        $areaId = $request->getParameter('area_id', 'trim');
        $keyword = $request->getParameter('bankName', 'trim');
        $params['conditions'] = array('bank_id' => $bankId, 'area_id' => $areaId);
        if ($keyword != '') {
            $params['conditions']['name'] = "%{$keyword}%";
        }
        $params['fields']="*";
        $params['order']="null";
        $params['page']='1';
        $params['pagesize']='2147483648';
        $url = "api/bank/getBankBranches";
        $result = PayApiClient::send($url, $params );
        if ($result->isSucess()) {
            $items = $result->getItems();
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "加载成功", $items);
        } else {
            Log::error("加载支行列表失败，接口返回：".$result->getMessage());
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, $result->getMessage(), null);
        }
    }

    /**
     * 加载支付通道，Ajax调用返回
     * @param HttpRequest $request
     */
    public function loadPayWay(HttpRequest $request)
    {
        if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
            echo "<h1>Access Deny!</h1>";
            die;
        }
        $params = array('conditions' => "");
        $url = "api/bank/loadPayways";
        $result = PayApiClient::send($url, $params);
        if ($result->isSucess()) {
            $items = $result->getItems();
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "加载支付通道成功", $items);
        } else {
            Log::error("加载支付通道失败,接口返回:".$result->getMessage());
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, $result->getMessage(), null);
        }
    }

    /**
     * 站内信页面
     * @param HttpRequest $request
     */
    public function remind(HttpRequest $request)
    {

        $remindService = Beans::get('message.messageRemind.service');
        $remindModel = Loader::model('messageRemind');

        $page = $request->getParameter('page');
        if($page<=0) $page = 1;
        $pagesize = 10;


        $this->setPagesize($pagesize);
        $this->setPage($page);

        $total = $remindModel->count(array('to_member_id' => $this->member_id, 'to_way'=>1,'app_id' => appId()));

        $items = $remindModel->getItems(array('to_member_id' => $this->member_id, 'to_way'=>1,'app_id' => appId()),'',array('to_time'=>-1),array($page,$pagesize));
        if (!empty($items)) {
            $ids = array();
            foreach ($items as $val) {
                $ids[] = $val['manager_id'];
            }
            $model = Loader::model("adminManager");
            $managers = $model->getItems(array('id' => array('$in' => $ids)));
            $managers = ArrayUtils::changeArrayKey($managers, 'id');
            foreach ($items as $key => $value) {
                $items[$key]['manager_name'] = $managers[$value['manager_id']]['name'];
                if ($items[$key]['manager_name'] == '') {

                    $items[$key]['manager_name'] = 'System';
                }
                $items[$key]['is_read'] = $remindService->getRemindIsreadText($items[$key]['is_read']);

            }
        }
        $this->memberPagemenu($total);

        $this->assign('total', $total);

        $this->assign("items", $items);
        $this->setView('person/person_mail');
    }

    /**
     * 站内信删除
     * @param HttpRequest $request
     */
    public function remind_delete(HttpRequest $request)
    {
        $id = $request->getParameter('id', 'intval');

        $remindService = Beans::get('message.messageRemind.service');

        $bool = $remindService->deletes(array('id' => $id, 'to_member_id' => $this->member_id,'to_way'=>1, 'app_id' => appId()));
        if ($bool) {

            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "站内信删除成功");

        } else {

            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "站内信删除失败");
        }

    }

    /**
     * 站内信置为已读状态
     * @param HttpRequest $request
     */
    public function remind_update_is_read(HttpRequest $request)
    {
        $id = $request->getParameter('id', 'intval');

        $remindService = Beans::get('message.messageRemind.service');

        $bool = $remindService->updates(array('is_read'=>1),array('id' => $id, 'to_member_id' => $this->member_id, 'to_way'=>1,'app_id' => appId()));
        if ($bool) {

            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "站内信标记已读成功");

        } else {

            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "站内信标记已读失败");
        }

    }

    /**
     * 编辑会员基本资料
     * @param HttpRequest $request
     */
    public function do_edit(HttpRequest $request){

        $user_id = $this ->_user ->__get('id');
        $data = $request->getParameter('data');
        if( $data['photo'] == ""){
            unset( $data['photo'] );
        }
        if($this -> __update($data, $user_id)){
            $this->_user->update($data);
            Log::info($user_id."修改了个人资料");
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,"修改成功",null);
        }else{
            Log::error($user_id."修改了个人资料失败");
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"修改失败",null);
        }
    }

    /**
     * 更新登陆手机号，修改手机号码数据发送到此处
     * @param HttpRequest $request
     */
    public function do_modifyMobile(HttpRequest $request)
    {
        if( $_SERVER['REQUEST_METHOD'] !== 'POST' ){
            echo "<h1>Access Deny!</h1>";die;
        }
        $data['username'] = $request -> getParameter('username');
        $data['password'] = passwd($request -> getParameter('password','trim'));

        $code = $request -> getParameter('vcode');
        $this -> timeOut();
        if ($code != $_SESSION['mpe_member']['vcode'])
        {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "验证码错误！");
        }
        if( $this -> _user -> __get('username') == $data['username'])
        {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "新的号码不能和原号码一致！");
        }
        $password = $this -> _user -> __get('password');
        if( $password != $data['password'] ){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "密码错误！");
        }
        $service = Beans::get($this->getServiceBean());
        if($service->count(array('username' => $data['username'])) > 0)
        {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"该号码已被注册，请更换新的号码！",null);
        }
        $id = $this -> _user -> __get('id');
        if($this -> __update($data, $id))
        {
            //修改成功后，发送站内信
            $messageService = Beans::get("message.messageRemind.service");
            $ruleName = "修改会员账号成功规则";
            $data = array('新会员手机号' => $data['username']);
            $messageService -> commandRemind($ruleName, $data,$id);
            Log::info("用户".$id."修改登陆手机号码为".$data['username']);
            $this -> _user ->logout();
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,"修改成功，请重新登陆！",null);
        } else {
            Log::error("用户".$id."修改登陆手机号码失败");
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"修改失败,请重试！",null);
        }
    }

    /**
     * 绑定大塑支付
     * @param HttpRequest $request
     */
    public function do_bind(HttpRequest $request)
    {
        $params['username'] = $request->getParameter('username');
        $params['password'] = md5($request->getParameter('password','trim'));
        $id = $this -> member_id;
        $params['app_userid'] = $id;
        $params['app_username'] = $this -> _user -> username;
        $url = "api/user/bind";
        $result = PayApiClient::send($url, $params);
        if ( $result->isSucess() ) {
            $items = $result->getItem();
            if( $items['sign_status'] != 1 ){
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"该账号未签约，请更换新的账号",null);
            }
            $service = Beans::get($this->getServiceBean());
            if($service->count(array('dasu_pay_id' => $items['id'],'del_status'=>0)) > 0)
            {
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"该账号已被绑定，请更换新的账号",null);
            }
            $data['dasu_pay_id'] = $items['id'];
            $data['updatetime'] = date('Y-m-d H:i:s');
            if( $items['ischecked'] == 2 ){
                $data['real_name'] = $items['virtual_name'];
                $data['ischecked'] = 1;
                $data['sign_status'] = 1;
            }
            if ( $service->update($data, $id) ) {
                $this->_user->update(array('dasu_pay_id' => $items['id']));
                Log::info("用户".$id."绑定到大塑账户：".$params['username']);
                AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, '绑定成功',null);
            } else {
                AjaxResult::ajaxFailtureResult();
            }
        } else {
            Log::error("用户".$id."绑定大塑账户失败，接口返回:".$result ->getMessage());
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '大塑账户或密码不正确',null);
        }
    }

    /**
     * 注册大塑账户
     * @param HttpRequest $request
     */
    public function do_register(HttpRequest $request)
    {
        $data = $request -> getParameter('data');
        $code = $request -> getParameter('vcode');
        if ($code != $_SESSION['mpe_member']['vcode'])
        {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "验证码错误！");
        }
        $data['username'] = $data['phone'];
        $data['contacter'] = $data['name'];
        unset($data['mobile']);
        unset($data['name']);
        $data['addtime'] = date('Y-m-d H:i:s');
        $data['updatetime'] = date('Y-m-d H:i:s');
        $data['password'] = md5(md5($data['password']));
        $data['type'] = '2'; //默认注册的是企业用户,注意一定是字符串，否则报签名错误
        unset($data['sure_pwd']);
        $id = $this -> _user -> __get('id');
        $url = "api/user/register";
        $result = PayApiClient::send($url, array('data' => $data));
        if ( $result->isSucess() ) {
            $params['dasu_pay_id'] = $result->getItem();
            $params['updatetime'] = date('Y-m-d H:i:s');
            $service = Beans::get($this->getServiceBean());
            if ( $service->update($params, $id) ) {
                $this -> _user ->update(array('dasu_pay_id'=>$params['dasu_pay_id']));
                $this -> _user ->updateSignInfo();
                //修改成功后，发送短信
                $rule = "REGISTER_SUCCESS";
                $mobile = $data['username'];
                $this -> sendBySaaSApi($rule,"",$mobile);
                Log::info($id."注册了大塑账户");
                unset($_SESSION['mpe_member']['vcode']);
                unset($_SESSION['mpe_member']['time']);
                AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, '注册成功',null);
            } else {
                //存在分布式事务的问题
                Log::error($id."注册大塑账户出现了分布式事物问题，回写大塑账户id失败，大塑账户id是：".$params['dasu_pay_id']);
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"注册失败",null);
            }
        } else {
            Log::error($id."注册大塑账户失败，接口返回：".$result->getMessage());
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,$result->getMessage(),null);
        }
    }

    /**
     * 修改交易密码
     * @param HttpRequest $request
     */
    public function do_tradePass(HttpRequest $request){
        $password = $request -> getParameter('password');
        $code = $request -> getParameter('vcode');
        $this -> timeOut();
        if( $code != $_SESSION['mpe_member']['vcode'] ){
            //unset($_SESSION['mpe_member']['vcode']);
            //unset($_SESSION['mpe_member']['time']);
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"验证码错误!",null);
        }
        $user_id = $this -> _user -> __get('dasu_pay_id');
        $url = "api/user/tradePass";
        $result = PayApiClient::send( $url,array('userid'=>$user_id,'password'=>passwd($password)) );
        if( $result -> isSucess() ){
            $mobile = $this -> _user -> getSignInfo('username');
            $username = $this -> _user -> getSignInfo('name');
            $this -> _user -> updateSignInfo();
            $this -> sendBySaaSApi("MODIFY_TRADE_SUCCESS",array('【username】'=>$username),$mobile);
            Log::info($user_id." 更新了交易密码");
            unset($_SESSION['mpe_member']['vcode']);
            unset($_SESSION['mpe_member']['time']);
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,"保存成功，请牢记你的交易密码!",null);
        }else{
            Log::error($user_id." 更新交易密码失败,接口返回:".$result -> getMessage());
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"保存失败，请稍后再试！",null);
        }
    }

    /**
     * 修改个人中心登陆密码
     * @param HttpRequest $request
     */
    public function do_modifyPassword(HttpRequest $request){

        $oldPassword = $request -> getParameter('old_pwd');
        $newPassword = $request -> getParameter('new_pwd');
        $surePassword = $request -> getParameter('sure_pwd');
        if($newPassword != $surePassword)
        {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"两次密码不一致",null);
        }
        if(passwd($oldPassword) != $this -> _user -> __get('password'))
        {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"原密码错误",null);
        }
        if(passwd($newPassword) == $this -> _user -> __get('password'))
        {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"不能与原密码一致",null);
        }
        if( $this -> __update(array('password'=> passwd($newPassword)),$this -> _user -> __get('id')) )
        {
            Log::info('用户'.$this -> _user -> __get('id').' 更新了登录密码');
            $smsService = Beans::get("message.messageRemind.service");
            $smsService->commandBySmsRemind("修改登录密码成功规则", "",$this->_user->__get('id'), $this->_user->__get('username'));
            $this -> _user -> logout();
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,"修改成功,请重新登陆",null);
        }else{
            Log::error('用户'.$this -> _user -> __get('id').' 更新登录密码失败');
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"修改失败,请联系客服",null);
        }
    }

    /**
     * 发送短信方法
     * @param HttpRequest $request
     */
    public function getSMS(HttpRequest $request){

        unset($_SESSION['mpe_member']['vcode']);
        $mobile = $request -> getParameter('mobile','trim');
        $flag = $request -> getParameter('msgType','trim');
        if( $mobile ) {
            if (!preg_match('/^\d{11}$/', $mobile )) {
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "手机格式错误", null);
            }
        }
        $code = rand(1000,9999);
        session_start();
        $_SESSION['mpe_member']['vcode'] = $code;
        //$_SESSION['sendMobile'] = array();
        if( !$flag || !in_array($flag,array(1,3,4)) ){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"发送失败",null);
        }
        $member_id = $this->_user->__get('id');
        switch( $flag ){
            case 1:
                //如果没有开启短信服务
                if( C('sms_open') != "on" ){
                    AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "短信服务未开启", null);
                }
                //修改会员账号
                $this -> checkTimeOut($mobile);
                $service = Beans::get($this->getServiceBean());
                if($service->count(array('username'=>$mobile,'del_status'=>0)) > 0)
                {
                    AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"该账号已存在，请更换新的账号",null);
                }
                $_SESSION['mpe_member']['time'] = time();
                $_SESSION['sendMobile'][] = $mobile;
                $rule = '修改会员账号验证码规则';
                $codeArray = array('验证码' =>$code);
                Log::info("{$mobile} 修改会员账号，验证码：".$code);
                $this -> sendByCommand($rule,$codeArray,$member_id,$mobile);
                break;
            case 3:
                $this -> checkTimeOut($mobile);
                $_SESSION['mpe_member']['time'] = time();
                $_SESSION['sendMobile'][] = $mobile;
                $rule = "MODIFY_TRADE_CODE";
                $mobile = $this -> _user -> getSignInfo('username');
                Log::info("{$mobile} 修改大塑账户交易密码，验证码：".$code);
                if($this -> sendBySaaSApi($rule,array('【code】'=>(string)$code),$mobile)) {
                    AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "发送成功", null);
                }else{
                    AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"发送失败",null);
                }
                break;//修改交易密码
            case 4:
                $this -> checkTimeOut($mobile);
                $this -> checkSaaSUser($mobile);
                $_SESSION['mpe_member']['time'] = time();
                $_SESSION['sendMobile'][] = $mobile;
                //AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "发送成功", null);
                $rule = "REGISTER_CODE";
                Log::info("{$mobile} 注册大塑账户，验证码：".$code);
                if($this -> sendBySaaSApi($rule,array('【code】'=>(string)$code),$mobile)) {
                    AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "发送成功", null);
                }else{
                    AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"发送失败",null);
                }
                break;//注册大塑账户
            default:
                unset($_SESSION['mpe_member']['vcode']);
                unset($_SESSION['mpe_member']['time']);
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"发送失败",null);
        }
    }

    /**
     * 调用RemindService发送短信，此类短信会被记录到数据库，且在后台可以直接看到
     * @param $rule string 模板规则
     * @param $codeArray array 数据内容
     * @param $member_id int 会员ID
     * @param $mobile string 接收短信的手机号码
     */
    protected function sendByCommand( $rule, $codeArray, $member_id, $mobile ){
        $smsService = Beans::get("message.messageRemind.service");
        $res = $smsService->commandBySmsRemind($rule, $codeArray,$member_id,$mobile);
        if ( $res ) {
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "发送成功", null);
        }else{
            unset($_SESSION['mpe_member']['vcode']);
            unset($_SESSION['mpe_member']['time']);
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"发送失败",null);
        }
    }

    /**
     * 调用SaaS接口发送短信
     * @param $rule
     * @param $data
     * @param $mobile
     * @return bool
     */
    protected function sendBySaaSApi( $rule, $data, $mobile ){
        $url = 'api/sms/getSMS';
        $result = PayApiClient::send($url,array('rule'=>$rule,'data'=>$data,'mobile'=>$mobile));
        if( $result -> isSucess() ){
            return true;
        }else{
            unset($_SESSION['mpe_member']['vcode']);
            unset($_SESSION['mpe_member']['time']);
            Log::error('调用SaaS短信接口失败，接口返回：'.$result->getMessage());
            return false;
        }
    }

    /**
     * 重复发送手机短信时间
     * @param $mobile
     */
    protected function checkTimeOut($mobile){
        if( !in_array($mobile,$_SESSION['sendMobile']) ){
            return;
        }
        if( !$_SESSION['mpe_member']['time'] ){
            return;
        }
        $seconds = time() - $_SESSION['mpe_member']['time'];
        if( $seconds < 120){
            $wait = 120 - $seconds;
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"请等待{$wait}秒后再尝试发送",null);
        }
    }

    /**
     * @param $mobile
     */
    protected function checkSaaSUser( $mobile ){
        $url = "api/user/checkUser";
        $result = PayApiClient::send( $url,array('mobile' => $mobile) );
        if( !$result->isSucess() ){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"账号已经存在,请直接绑定即可！",null);
        }

    }

    /**
     * @override 更新数据
     * @author Liuyi
     * @Create 2016-11-1 11:13:50
     * @param array $data
     * @param $id
     * @return bool
     */
    public function __update(array $data, $id) {

        if ( empty($data) || empty($id) ) return false;

        $data['updatetime'] = date('Y-m-d H:i:s');

        $service = Beans::get($this->getServiceBean());
        if ( $service->update($data, $id) !==false ) {
            return true;
        } else {
            return false;
        }

    }

}
